<template>
  <el-upload
    class="avatar-uploader"
    :action="action"
    :headers="headers"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
  >
    <img v-if="imageUrl" :src="imageFullUrl" class="avatar" alt="" />
    <el-icon v-else class="avatar-uploader-icon">
      <Plus />
    </el-icon>
  </el-upload>
</template>
<script setup lang="ts">
import { Plus } from "@element-plus/icons-vue";
import { fileApi } from "@/api/file";
// 上传文件的地址
const action = ref(fileApi.uploadUrl());
// 请求上传的头部
const headers = ref(fileApi.authHeader());
const props = defineProps({
  pictureUrl: {
    type: String,
    default: ""
  },
  // 宽
  width: {
    type: Number,
    default: 80
  },
  // 高
  height: {
    type: Number,
    default: 80
  },
  // 类型
  type: {
    type: String,
    default: "resize"
  }
});
const { pictureUrl } = toRefs(props);

const imageUrl = ref("");
imageUrl.value = pictureUrl.value;
const emits = defineEmits(["imageSrc"]);

function handleAvatarSuccess(res: any) {
  if (res.fileSrc) {
    ElMessage({
      message: "上传成功",
      type: "success"
    });
    imageUrl.value = res.fileSrc;
    emits("imageSrc", res.fileSrc);
  }
}
watchEffect(() => {
  imageUrl.value = props.pictureUrl;
});

const imageFullUrl = computed(() =>
  fileApi.imageUrl(imageUrl.value, props.width, props.height, props.type)
);
</script>
<style setup lang="scss">
.avatar-uploader {
  .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }

  .el-upload {
    border: 1px dashed var(--el-border-color);
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 26px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    text-align: center;
  }
}
</style>
